<?php
class UserControl extends CommonControl
{
	protected $pageConfig;

	//初始化
	public function init()
	{
		parent::init();
		$this->pageConfig = array(
			'base_url'   => '',
			'total_rows' => 0,
			'per_page'   => 15,
			'num_links'  => 2,
			'page_container_tag_style' => 'page',
			'num_tag_style'	=> 'num_page',
		);
	}

	//访问规则，
	public function rules()
	{
		return array(
			//允许未登陆用户访问login，logout动作
			array(
				'access' => 'allow',
				'actions'=> array('login','logout'),
				'user'   => '?',
			),

			//所有动作都必须登陆后才能访问，login,logout规则放前面，以防覆盖。
			array(
				'access'  => 'allow',
				'actions' => array('*'),
				'user'    => '@',
			),
		);
	}

	//登陆
	public function actionLogin()
	{
		$token = new dpEncrypt();
		$bread = $this->getBreadCrumbs(array('首页' => 'index','登陆' => '')); 
		$errorMsg = '';
		if(isset($_POST['token']))
		{
			if($token->decode($_POST['token'], 'DuolamPHP') != 'login_auth') 
				D::error('非法操作');
			D::import('app:component.userIdentity');
			$username = trim(htmlspecialchars($_POST['username']));
			$password = trim(htmlspecialchars($_POST['password']));
			$Identity = new userIdentity($username, $password);
			if(!dpImage::checkVerify('code',trim(htmlspecialchars($_POST['code']))))
				$errorMsg = '验证码不正确';
			if(empty($errorMsg) && $Identity->authenticate())
			{
				$this->user->login($Identity);
				header('Location:'.D::createUrl('index'));
			}
			else
				$errorMsg = empty($errorMsg) ? $Identity->getError() : $errorMsg;
		}
		$var = array(
			'token_code'   => $token->encode('login_auth','DuolamPHP'),
			'bread_crumbs' => $bread,
			'error_msg'	   => $errorMsg,
		);
		unset($bread, $username, $password, $errorMsg, $token, $Identity);
		$this->render('login', $var);
	}

	//退出
	public function actionLogout()
	{
		$this->user->logout();
		header('Location:'.D::createUrl('index'));
	}

	//删除评论
	public function actionDeleteReply($id = 0) 
	{
		if($this->isAjax())
		{
			if(!D::app()->user()->checkAccess($this->getAction(), 'user'))
				$this->ajaxReturn(array('code'=>1, 'msg'=>'没有权限操作'));
			if((int)$id == 0) $this->ajaxReturn(array('code'=>1, 'msg'=>'你想SQL注入？'));
			$posts = replyModel::model()->findByPk($id);
			if(replyModel::model()->deleteByPk($id))
			{
				$post = postsModel::model()->findByPk($posts['posts_id']);
				postsModel::model()->reply_number = $post['reply_number'] - 1;
				postsModel::model()->updateByPk($posts['posts_id']);
				$this->ajaxReturn(array('code'=>0));
			}else
				$this->ajaxReturn(array('code'=>1, 'msg'=>'删除失败'));
		}
		else
		{
			$this->ajaxReturn(array('code'=>1, 'msg'=>'非法操作'));
		}
	}

	//单页管理
	public function actionPageManage($page = 1)
	{
		if(D::app()->user()->checkAccess($this->getAction(), 'user'))
		{
			$pm = pageModel::model();
			$this->pageConfig['base_url']   = 'user/pageManage';
			$this->pageConfig['total_rows'] = count($pm->findsByAttribute('id'));
			$pageObj = new dpPage($this->pageConfig);
			$pageList = $pm->limit($pageObj->getSqlLimit())->finds();
			$var = array(
				'page_list' => $pageList,
				'pages' => $pageObj->display(),
				'page'  => $page,
				'bread_crumbs' =>$bread = $this->getBreadCrumbs(array('首页' => 'index','单页管理' => ''))
			);
			$this->render('user/page_manage', $var);
		} 
		else D::error('你没有权限操作');
	}

	//删除单页
	public function actionDeletePage($id = 0)
	{
		if(D::app()->user()->checkAccess($this->getAction(), 'user'))
		{
			if(pageModel::model()->deleteByPk((int)$id))
				$this->ajaxReturn(array('code'=>0));
			else
				$this->ajaxReturn(array('code'=>1, 'msg'=>'删除失败'));
		}
		else $this->ajaxReturn(array('code'=>1, 'msg'=>'没有权限删除单页'));
	}

	//添加单页
	public function actionPageAdd()
	{
		if(D::app()->user()->checkAccess($this->getAction(), 'user'))
		{
			if(!empty($_POST) && pageModel::model()->insert($_POST))
			{
				header('Location:'.D::createUrl('user/pageAdd'));
				exit;
			}
			$var = array(
				'bread_crumbs' =>$bread = $this->getBreadCrumbs(array('首页' => 'index','添加单页' => ''))
			);
			$this->render('user/page_add', $var);
		}
		else D::error('没有权限添加单页');
	}

	//文章管理
	public function actionArticleManage($page = 1)
	{
		if(D::app()->user()->checkAccess($this->getAction(), 'user'))
		{
			$pm = postsModel::model();
			$this->pageConfig['base_url']   = 'user/artilceManage';
			$this->pageConfig['total_rows'] = count($pm->findsByAttribute('id'));
			$pageObj = new dpPage($this->pageConfig);
			$articleList = $pm->limit($pageObj->getSqlLimit())->sort_time()->finds();
			$var = array(
				'article_list' => $articleList,
				'pages' => $pageObj->display(),
				'page'  => $page,
				'bread_crumbs' =>$bread = $this->getBreadCrumbs(array('首页' => 'index','文章管理' => ''))
			);
			$this->render('user/article_manage', $var);
		} 
		else D::error('你没有权限操作');
	}

	//删除文章
	public function actionDeleteArticle($id = 0)
	{
		if(D::app()->user()->checkAccess($this->getAction(), 'user'))
		{
			if(postsModel::model()->deleteByPk((int)$id) && replyModel::model()->deletes('posts_id='.(int)$id))
				$this->ajaxReturn(array('code'=>0));
			else
				$this->ajaxReturn(array('code'=>1, 'msg'=>'删除失败'));
		}
		else $this->ajaxReturn(array('code'=>1, 'msg'=>'没有权限删除文章'));
	}

	//发布文章
	public function actionArticleAdd()
	{
		if(D::app()->user()->checkAccess($this->getAction(), 'user'))
		{
			if(!empty($_POST))
			{
				$_POST['create_time'] = TIME;
				$_POST['views']		  = 0;
				$_POST['reply_number']= 0;
				if(postsModel::model()->insert($_POST))
				{
					header('Location:'.D::createUrl('user/pageAdd'));
					exit;
				}
			}
			$var = array(
				'bread_crumbs' =>$bread = $this->getBreadCrumbs(array('首页' => 'index','发布文章' => ''))
			);
			$this->render('user/article_add', $var);
		}
		else D::error('没有权限发布文章');
	}

	//会员管理
	public function actionUserManage($page = 1)
	{
		if(D::app()->user()->checkAccess($this->getAction(), 'user'))
		{
			$urm = userRoleModel::model();
			$this->pageConfig['total_rows'] = count($urm->user()->role()->findsByAttribute('uid'));
			$pageObj = new dpPage($this->pageConfig);
			$userList = $urm->limit($pageObj->getSqlLimit())->user()->role()->findsByAttribute('uid');
			$var = array(
				'user_role' => roleModel::model()->findsByAttribute(array('rid','role_name')),
				'user_list' => $userList,
				'pages' => $pageObj->display(),
				'page'  => $page,
				'bread_crumbs' =>$bread = $this->getBreadCrumbs(array('首页' => 'index','用户管理' => ''))
			);
			$this->render('user/user_manage', $var);
		} 
		else D::error('你没有权限操作');
	}

	//添加会员
	public function actionUserAdd()
	{
		if(D::app()->user()->checkAccess($this->getAction(), 'user'))
		{
			$error = '';
			if(!empty($_POST))
			{
				$username = $_POST['username'];
				$user = userModel::model()->findByAttribute('uid', "username='$username'");
				if(!empty($user))
					$error = '用户已存在';
				else
				{
					$rid = $_POST['rid'];
					$_POST['gid'] = $_POST['is_extends'] = 0;
					$_POST['password'] = md5(md5($_POST['password'].'_dp'));
					userModel::model()->insert($_POST);
					$uid = userModel::model()->uid;
					userRoleModel::model()->insert(array('uid'=>$uid, 'rid'=>$rid));
					header('Location:'.D::createUrl('user/userAdd'));
					exit;
				}
			}
			$var = array(
				'error' => $error,
				'role_list' => roleModel::model()->findsByAttribute(array('rid', 'role_name')),
				'bread_crumbs' =>$bread = $this->getBreadCrumbs(array('首页' => 'index','添加用户' => ''))
			);
			$this->render('user/user_add', $var);
		}
		else D::error('没有权限添加用户');
	}

	//更改是否是超级管理员
	public function actionChangeUserManage($uid)
	{
		if(D::app()->user()->checkAccess($this->getAction(), 'user'))
		{
			$uid  = (int)$uid;
			$user = userModel::model()->findByPk($uid);
			empty($user) && $this->ajaxReturn(array('code'=>1, 'msg'=>'会员不存在'));
			if($user['is_manage'])
				userModel::model()->is_manage = 0;
			else
				userModel::model()->is_manage = 1;
			if(userModel::model()->updateByPk($uid))
				$this->ajaxReturn(array('code'=>0));
			else
				$this->ajaxReturn(array('code'=>1, 'msg'=>'更改失败'));
		}
		else $this->ajaxReturn(array('code'=>1, 'msg'=>'你没有权限操作'));
	}

	//更改是否是激活
	public function actionChangeUserActiv($uid)
	{
		if(D::app()->user()->checkAccess($this->getAction(), 'user'))
		{
			$uid  = (int)$uid;
			$user = userModel::model()->findByPk($uid);
			empty($user) && $this->ajaxReturn(array('code'=>1, 'msg'=>'会员不存在'));
			if($user['is_activation'])
				userModel::model()->is_activation = 0;
			else
				userModel::model()->is_activation = 1;
			if(userModel::model()->updateByPk($uid))
				$this->ajaxReturn(array('code'=>0));
			else
				$this->ajaxReturn(array('code'=>1, 'msg'=>'更改失败'));
		}
		else $this->ajaxReturn(array('code'=>1, 'msg'=>'你没有权限操作'));
	}

	//更改用户的角色
	public function actionChangeUserRole($uid, $rid)
	{
		if(D::app()->user()->checkAccess($this->getAction(), 'user'))
		{
			$uid = (int)$uid;
			$rid = (int)$rid;
			userRoleModel::model()->updates(array('rid'=>$rid), 'uid='.$uid);
			$info = roleModel::model()->findByPk($rid);
			$this->ajaxReturn(array('code'=>0, 'name'=>$info['role_name']));
		} 
		else $this->ajaxReturn(array('code'=>1, 'msg'=>'你没有权限操作'));
	}

	//删除会员
	public function actionDeleteUser($id = 0)
	{
		if(D::app()->user()->checkAccess($this->getAction(), 'user'))
		{
			if(userModel::model()->deleteByPk((int)$id) && userRoleModel::model()->deletes('uid='.(int)$id))
				$this->ajaxReturn(array('code'=>0));
			else
				$this->ajaxReturn(array('code'=>1, 'msg'=>'删除失败'));
		}
		else $this->ajaxReturn(array('code'=>1, 'msg'=>'没有权限删除会员'));
	}

	//角色管理
	public function actionRoleManage($page = 1)
	{
		if(D::app()->user()->checkAccess($this->getAction(), 'user'))
		{
			$rm = roleModel::model();
			$this->pageConfig['total_rows'] = count($rm->findsByAttribute('rid'));
			$pageObj = new dpPage($this->pageConfig);
			$userList = $rm->limit($pageObj->getSqlLimit())->finds();
			$var = array(
				'role_list' => $userList,
				'pages' => $pageObj->display(),
				'page'  => $page,
				'bread_crumbs' =>$bread = $this->getBreadCrumbs(array('首页' => 'index','角色管理' => ''))
			);
			$this->render('user/role_manage', $var);
		} 
		else D::error('你没有权限操作');
	}

	//添加会员
	public function actionRoleAdd()
	{
		if(D::app()->user()->checkAccess($this->getAction(), 'user'))
		{
			$error = '';
			if(!empty($_POST))
			{
				$role_name = $_POST['role_name'];
				$role = roleModel::model()->findByAttribute('rid', "role_name='$role_name'");
				if(!empty($role))
					$error = '角色已存在';
				else
				{
					$_POST['father_role_id'] = $_POST['is_role_enabled'] = 0;
					roleModel::model()->insert($_POST);
					$rid = roleModel::model()->rid;
					$actions = implode('|', $_POST['behavior']);
					$behaviorName = $_POST['role_name'] . '权限';
					behaviorModel::model()->insert(array('access_action'=>$actions, 'rid' => $rid, 'behavior_name' => $behaviorName));
					header('Location:'.D::createUrl('user/roleAdd'));
					exit;
				}
			}
			$var = array(
				'error' => $error,
				'behavior_list' => $this->getBehavior(), //行为权限列表
				'bread_crumbs' =>$bread = $this->getBreadCrumbs(array('首页' => 'index','添加角色' => ''))
			);
			$this->render('user/role_add', $var);
		}
		else D::error('没有权限添加角色');
	}

	//角色权限分配
	public function actionAuthManage($rid = 1)
	{
		if(D::app()->user()->checkAccess($this->getAction(), 'user'))
		{
			$bh = behaviorModel::model()->findByAttribute('*', 'rid='.(int)$rid);
			if(!empty($_POST['behavior']) && !empty($bh))
			{
				$bid = $bh['bid'];
				$actions = implode('|', $_POST['behavior']);
				if(behaviorModel::model()->updateByPk($bid, array('access_action'=>$actions)))
				{
					header('Location:'.D::createUrl('user/authManage', array('id'=>$rid)));
					exit;
				}
			}
			if(empty($bh))
				$actions = array();
			else
				$actions = explode('|', $bh['access_action']);
			$var = array(
				'actions' => $actions,
				'behavior_list' => $this->getBehavior(), //行为权限列表
				'bread_crumbs' =>$bread = $this->getBreadCrumbs(array('首页' => 'index', '角色管理' => 'user/roleManage', '角色权限分配' => ''))
			);
			$this->render('user/auth_manage', $var);
		} 
		else D::error('你没有权限操作');
	}

	/**
	 * 权限列表
	 */
	protected function getBehavior()
	{
		return array(
			'单页权限：' => array(
				'单页管理' => 'pageManage',
				'单页添加' => 'pageAdd',
				'单页删除' => 'deletePage'
			),
			'文章权限：' => array(
				'文章管理' => 'articleManage',
				'文章添加' => 'articleAdd',
				'文章删除' => 'deleteArticle',
			),
			'用户权限：' => array(
				'用户管理'		 => 'userManage',
				'用户添加'		 => 'userAdd',
				'用户删除'		 => 'deleteUser',
				'更改超级管理员' => 'changeUserManage',
				'更改用户激活'   => 'changeUserActiv',
				'更改用户角色'   => 'changeUserRole'
			),
			'角色权限：' => array(
				'角色管理' => 'roleManage',
				'角色添加' => 'roleAdd',
				'角色删除' => 'deleteRole',
				'角色权限管理' => 'authManage',
			)
		);
	}
}

?>